from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework import viewsets
from rest_framework.response import Response
from .serializers import StudentSerializer, ClassesSerializer
from .models import Student, Classes
from rest_framework.status import HTTP_404_NOT_FOUND, HTTP_204_NO_CONTENT

# Create your views here.
'''
    视图集
    list 查询全部  create 增加  retrieve 查询单条  update 修改  destroy 删除
'''
# class StudentViewSet(viewsets.ViewSet):
#     def list(self, request):
#         #Student.objects.all() 从当前模型类里面查询全部的数据
#         #students为模型对象，查询集，在前端无法直接展示数据
#         students = Student.objects.all()
#         #many=True 多条数据的操作需要加上
#         #StudentSerializer 表示自己新建的序列化器
#         serializer = StudentSerializer(students, many=True);
#         #serializer.data 表示从当前的序列化器把数据读取出来
#         return Response(serializer.data)
#
#     def create(self, request):
#         # 获取前端传入的请求体并实例化序列化器，进行反序列化
#         serializer = StudentSerializer(data=request.data)
#         # 调用is_vaild进行效验
#         serializer.is_valid(raise_exception=True)
#         # 调用save方法进行保存(create)
#         serializer.save()
#         # 返回响应
#         return Response(serializer.data)
#
#     def retrieve(self, request, pk):
#         # 根据参数获取具体的数据  get请求没有数据会报错，需要使用异常处理
#         try:
#             student = Student.objects.get(id=pk)
#         except Student.DoesNotExist:
#             return Response(status=HTTP_404_NOT_FOUND)
#
#         serializer = StudentSerializer(student)  # 根据对象转json 序列化
#         return Response(serializer.data)
#
#     def update(self, request, pk):
#         # 查询
#         try:
#             student = Student.objects.get(id=pk)
#         except Student.DoesNotExist:
#             return Response(status=HTTP_404_NOT_FOUND)
#         # 反序列化
#         serializer = StudentSerializer(student, data=request.data)
#         # 效验
#         serializer.is_valid(raise_exception=True)
#         # 保存 update
#         serializer.save()
#         return Response(serializer.data)
#
#     def destroy(self, request, pk):
#         # 查询
#         try:
#             student = Student.objects.get(id=pk)
#         except Student.DoesNotExist:
#             return Response(status=HTTP_404_NOT_FOUND)
#         student.delete()
#         return Response(status=HTTP_204_NO_CONTENT)
class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.filter(is_delete=False)  # 定义视图集使用的查询集
    serializer_class = StudentSerializer   # 视图集使用的序列化器类


class ClassesViewSet(viewsets.ModelViewSet):
    queryset = Classes.objects.filter(is_delete=False)  # 定义视图集使用的查询集
    serializer_class = ClassesSerializer   # 视图集使用的序列化器类

    @action(methods=['get'], detail=False)
    def last(self, request):
        # 查询出班级的最后一条数据
        classes = Classes.objects.last()
        # 将查询出来的模型对象转化为json数据格式，然后进行返回
        return Response(self.get_serializer(classes).data)


